package com.ksyun.timeservice.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ksyun.timeservice.domain.dto.HeartBeat;
import com.ksyun.timeservice.domain.dto.ServiceInstance;
import com.ksyun.timeservice.service.TimeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
@RequiredArgsConstructor
public class TimeServiceImpl implements TimeService {
    private  ServiceInstance serviceInstance;
    private static String serviceId= UUID.randomUUID().toString();
    @Override
    public String getCurrentDateTime(String style) {
        switch (style != null ? style : "") {
            case "full":
                return formatCurrentDateTime("yyyy-MM-dd HH:mm:ss");
            case "date":
                return formatCurrentDateTime("yyyy-MM-dd");
            case "time":
                return formatCurrentDateTime("HH:mm:ss");
            case "unix":
                return String.valueOf(System.currentTimeMillis());
            default:
                return "Invalid style parameter.";
        }
    }
    private String formatCurrentDateTime(String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        return sdf.format(new Date());
    }

    private ScheduledExecutorService scheduledExecutorService;
    private Runnable registrationTask;
    @Override
    public void awake(ServiceInstance serviceInstance) {
        this.serviceInstance=serviceInstance;
        // 如果定时任务已经启动，则不再启动
        if (scheduledExecutorService != null && !scheduledExecutorService.isShutdown()) {
            return;
        }
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

        // 定义定时任务
        registrationTask = () -> {
            try {
                // 这里将调用发送 POST 请求的逻辑，使用 sendPostRequest 方法
                sendPostRequest(serviceInstance);
            } catch (Exception e) {

            }
        };
        // 每隔一定时间（例如每 60 秒）执行一次注册
        scheduledExecutorService.scheduleAtFixedRate(registrationTask, 0, 59, TimeUnit.SECONDS);
    }

    @Override
    public void sleep(ServiceInstance serviceInstance) {
        this.serviceInstance=null;
        // 关闭定时任务
        if (scheduledExecutorService != null) {
            scheduledExecutorService.shutdownNow(); // 关闭定时任务
            scheduledExecutorService = null;
        }

    }

    @Override
    public String getServiceID() {
        return serviceInstance.getServiceId();
    }

    private void sendPostRequest(ServiceInstance serviceInstance) throws Exception{
        // 实现向注册中心发送 POST 请求的逻辑
        HeartBeat heartBeat=new HeartBeat(serviceInstance.getServiceId(),serviceInstance.getIpAddress(),serviceInstance.getPort());
        //向客户端发送请求
        ObjectMapper objectMapper=new ObjectMapper();
        String json = objectMapper.writeValueAsString(heartBeat);
        String ipAddress = serviceInstance.getIpAddress();
        int port = serviceInstance.getPort();
        // 尝试调用远程的 heart
        String url = "http://localhost:8880/api/heartbeat";

        HttpPost httpPost = new HttpPost(url);
        StringEntity entity = new StringEntity(json);
        // 设置 Content-Type
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setEntity(entity);
        // 设置超时
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(2000) // 连接超时设置为0.2秒
                .setSocketTimeout(2000)  // 读取超时设置为0.2秒
                .build();
        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();

        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            // 处理响应,不需要处理
        } catch (Exception e) {
        } finally {
            httpClient.close(); // 确保客户端被关闭
        }
    }

    public static void register() throws Exception{
        String serviceName="time-service";
        int port=8980;
        String ipAddress="127.0.0.1";
        ServiceInstance serviceInstance=new ServiceInstance(serviceName,serviceId,ipAddress,port);
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(serviceInstance);

        String url="http://localhost:8880/api/register";

        HttpPost httpPost = new HttpPost(url);
        StringEntity entity = new StringEntity(json);
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-Type", "application/json");
        // 设置超时
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(1000) // 连接超时设置为0.2秒
                .setSocketTimeout(1000)  // 读取超时设置为0.2秒
                .build();
        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();

        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            // 处理响应,不需要处理
        } catch (Exception e) {
        } finally {
            httpClient.close(); // 确保客户端被关闭
        }
    }
    public static void unregister() throws Exception{
        String serviceName="time-service";
        int port=8980;
        String ipAddress="127.0.0.1";
        ServiceInstance serviceInstance=new ServiceInstance(serviceName,serviceId,ipAddress,port);
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(serviceInstance);
        String url="http://localhost:8880/api/unregister";
        HttpPost httpPost = new HttpPost(url);
        StringEntity entity = new StringEntity(json);
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-Type", "application/json");
        // 设置超时
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(1000) // 连接超时设置为0.2秒
                .setSocketTimeout(1000)  // 读取超时设置为0.2秒
                .build();
        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            // 处理响应,不需要处理
        } catch (Exception e) {

        } finally {
            httpClient.close(); // 确保客户端被关闭
        }
    }

}

